#include "safequeue.h"

SafeQueue::SafeQueue(int capacity, QObject* parent)
    : QObject(parent)
    , capacity_(capacity)
    , warningSign_(false)
    , stopped_(false)
{}

SafeQueue::~SafeQueue()
{
    clear();
}

bool SafeQueue::enqueue(const QImage& image)
{
    QMutexLocker locker(&mutex_);
    // 队列已停止时直接 reutrn false
    if (stopped_) return false;

    while (queue_.size() >= capacity_ && !stopped_)
    {
        // 队列已满，只在第一次时发出警告信号，避免一直发
        if (!warningSign_)
        {
            warningSign_ = true;
            emit queueFull();
        }
        notFull_.wait(&mutex_, 500);
    }

    if (stopped_) return false;

    // 队列有空间时，重置警告标志
    if (queue_.size() < capacity_)
    {
        warningSign_ = false;
    }

    queue_.enqueue(image);
    notEmpty_.wakeOne();
    return true;
}

bool SafeQueue::dequeue(QImage& image)
{
    QMutexLocker locker(&mutex_);
    // 队列已停止时直接 reutrn false
    if (stopped_) return false;

    while (queue_.isEmpty() && !stopped_)
    {
        notEmpty_.wait(&mutex_, 500);
    }

    if (stopped_ || queue_.isEmpty()) return false;

    image = queue_.dequeue();
    notFull_.wakeOne();
    return true;
}

int SafeQueue::size() const
{
    QMutexLocker locker(&mutex_);
    return queue_.size();
}

bool SafeQueue::isEmpty() const
{
    QMutexLocker locker(&mutex_);
    return queue_.isEmpty();
}

bool SafeQueue::isFull() const
{
    QMutexLocker locker(&mutex_);
    return queue_.size() >= capacity_;
}

void SafeQueue::clear()
{
    QMutexLocker locker(&mutex_);
    queue_.clear();
    warningSign_ = false;
}

void SafeQueue::wakeAll()
{
    QMutexLocker locker(&mutex_);
    notFull_.wakeAll();
    notEmpty_.wakeAll();
}

void SafeQueue::reset()
{
    QMutexLocker locker(&mutex_);
    stopped_ = false;       // 重置停止标志
    warningSign_ = false;   // 重置警告标志
    queue_.clear();         // 清空队列数据
}
